import os
import json
import queue
import sys
import wave
import sounddevice as sd
from vosk import Model, KaldiRecognizer, SetLogLevel

# 设置FFmpeg路径
ffmpeg_path = os.path.join(os.getcwd(), "ffmpeg", "bin")
os.environ["PATH"] = ffmpeg_path + os.pathsep + os.environ["PATH"]

from pydub import AudioSegment

# 验证
print(AudioSegment.ffmpeg)  # 应输出FFmpeg路径

# 设置日志级别
SetLogLevel(0)


def convert_mp3_to_wav_with_parameters(input_mp3_path, output_wav_path):
    """
    将MP3文件转换为指定参数的WAV文件
    参数：
    - 采样率：8kHz (8000)
    - 位深度：16bit (sample_width=2)
    - 声道：单声道 (channels=1)
    """
    try:
        # 检查输入文件是否存在
        if not os.path.exists(input_mp3_path):
            raise FileNotFoundError(f"输入文件不存在: {input_mp3_path}")

        # 加载MP3文件
        print(f"正在加载文件: {input_mp3_path}")
        audio = AudioSegment.from_mp3(input_mp3_path)

        # 显示原始文件信息
        print(f"原始文件信息:")
        print(f"  采样率: {audio.frame_rate} Hz")
        print(f"  声道数: {audio.channels}")
        print(f"  位深度: {audio.sample_width * 8} bit")
        print(f"  时长: {len(audio) / 1000:.2f} 秒")

        # 设置目标参数
        print("正在设置音频参数...")
        audio = audio.set_frame_rate(8000)  # 8kHz采样率
        audio = audio.set_channels(1)  # 单声道
        audio = audio.set_sample_width(2)  # 16位深度

        # 显示转换后文件信息
        print(f"转换后文件信息:")
        print(f"  采样率: {audio.frame_rate} Hz")
        print(f"  声道数: {audio.channels}")
        print(f"  位深度: {audio.sample_width * 8} bit")
        print(f"  时长: {len(audio) / 1000:.2f} 秒")

        # 导出为WAV文件
        print(f"正在导出到: {output_wav_path}")
        audio.export(output_wav_path, format="wav")

        print("转换完成！")
        return True

    except Exception as e:
        print(f"转换过程中发生错误: {e}")
        return False


def speech_recognition(model_path, wav_path):
    """
    实时语音识别实现
    """
    wf = wave.open(wav_path, "rb")
    if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
        print("Audio file must be WAV format mono PCM.")
        sys.exit(1)
    # 加载Vosk模型
    model = Model(model_path)
    rec = KaldiRecognizer(model, wf.getframerate())
    rec.SetWords(True)
    rec.SetPartialWords(True)

    while True:
        data = wf.readframes(4000)
        if len(data) == 0:
            break
        if rec.AcceptWaveform(data):
            obj = json.loads(rec.Result())
            # print(json.loads(rec.Result())['text'])
            print(obj.get('text'))
        # else:
        #     print(rec.PartialResult())

    # print(rec.FinalResult())


# 使用示例
if __name__ == "__main__":
    input_file = "./audios/liuxue-3.MP3"
    output_file = "./audios/liuxue-3.wav"
    convert_mp3_to_wav_with_parameters(input_file, output_file)

    # 下载中文模型：https://alphacephei.com/vosk/models
    model_path = "./models/vosk-model-cn-0.22"  # 替换为你的模型路径
    speech_recognition(model_path, output_file)
